<template>
  <div class="app-container customer-div">
    <div>
      <el-radio-group v-model="listQuery.tab" size="small" @change="changeTab">
        <el-radio-button label="all">全部</el-radio-button>
        <el-radio-button label="unpaid">未付款</el-radio-button>
        <el-radio-button label="application">申请中</el-radio-button>
      </el-radio-group>
    </div>
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="120px">
        <el-form-item label="单据编号：">
          <el-input v-model="listQuery.entrySn" clearable></el-input>
        </el-form-item>
        <el-form-item label="加工商：">
          <el-input v-model="listQuery.agentProcessor" clearable></el-input>
        </el-form-item>
        <el-form-item label="原料采购订单号：">
          <el-input v-model="listQuery.materialOrderSn" clearable></el-input>
        </el-form-item>
        <el-form-item label="单据日期：">
          <el-date-picker
            v-model="listQuery.createTime"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="(item,index ) in userOptionList"
              :key="index"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工费付款状态：" v-if="listQuery.tab == 'all'">
          <el-select v-model="listQuery.processPayState" filterable placeholder="请选择" clearable style="width:100px">
            <el-option :key="0" label="未付款" :value="0"></el-option>
            <el-option :key="10" label="申请中" :value="10"></el-option>
            <el-option :key="20" label="已付款" :value="20"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
            :loading="btnloading5"
            @click="downloadExcel()"
            type="primary">
            导出
          </el-button>
          <el-button
            @click="showPop()"
            type="primary">
            付款
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        ref="multipleTable"
        row-key="pegId"
        @selection-change="handleSelectionChange"
        v-loading="listLoading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 20px">
        <!--只有状态为未付款的记录可以选中-->
        <el-table-column type="selection" :reserve-selection="true" width="60" align="center" :selectable="selectable" fixed="left"></el-table-column>
        <el-table-column  label="单据类型"  align="center" prop="orderSn" min-width="100">
          <template slot-scope="scope">
              {{ scope.row.entryType }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="单据编号" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.entrySn }}
          </template>
        </el-table-column>
        <el-table-column
          label="单据日期"
          align="center" min-width="100">
          <template slot-scope="scope">
            {{ scope.row.entryTime }}
          </template>
        </el-table-column>
        <el-table-column
          min-width="150"
          label="采购订单号"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.purchaseOrderSn }}
          </template>
        </el-table-column>
        <el-table-column
          min-width="150"
          prop="agentProcessor"
          label="加工商"
          align="center">
        </el-table-column>
        <el-table-column
          align="center"
          min-width="150"
          label="商品名称">
          <template  slot-scope="scope">
            {{ scope.row.goodsName }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="批号">
          <template  slot-scope="scope">
            {{ scope.row.goodsBatchNo }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="100"
          label="仓库">
          <template  slot-scope="scope">
            {{ scope.row.goodsWarehouse }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="100"
          label="数量">
          <template  slot-scope="scope">
            {{ scope.row.goodsNum }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="100"
          label="单位">
          <template  slot-scope="scope">
            {{ scope.row.goodsUnit }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="单价">
          <template  slot-scope="scope">
            {{ scope.row.goodsPrice }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="业务员">
          <template  slot-scope="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>

        <el-table-column
          header-align="center"
          align="left"
          min-width="150"
          label="备注">
          <template  slot-scope="scope">
            {{ scope.row.goodsRemark }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="150"
          label="原采购订单号">
          <template  slot-scope="scope">
            {{ scope.row.materialOrderSn }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          min-width="100"
          label="原料单价">
          <template  slot-scope="scope">
            {{ scope.row.materialPrice }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="加工费">
          <template  slot-scope="scope">
            {{ scope.row.processingFee }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="加工费总额">
          <template  slot-scope="scope">
            {{ scope.row.processingFeeAmount }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="100"
          label="加工费状态">
          <template  slot-scope="scope">
            {{ scope.row.processPayState }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="付款时间">
          <template  slot-scope="scope">
            {{ scope.row.processPayTime }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          min-width="150"
          label="付款申请编号">
          <template  slot-scope="scope">
            {{ scope.row.processPayApplySn }}
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          width="100"
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="toInfo(scope.row)">查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20,50,100]"
        :total="count">
      </el-pagination>
    </div>

    <!--付款申请-->
    <el-dialog
      :close-on-click-modal="false"
      title="付款申请"
      :visible.sync="dialogVisible"
      width="800px">
      <el-form :model="payForm" size="mini" label-width="100px" ref="payForm" :rules="rules">
        <el-form-item label="收款方：" >
            {{payForm.agentProcessor}}
        </el-form-item>
        <el-form-item label="付款方："  >
            <el-radio-group v-model="payForm.fromCompany">
                <el-radio label="塑盟"></el-radio>
                <el-radio label="普利成"></el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="入库明细："  >
             <el-table :data="selectProduct" border style="width: 100%;" max-height="250">
                 <el-table-column
                   align="center"
                   min-width="150"
                   label="入库单号">
                   <template  slot-scope="scope">{{scope.row.entrySn}}</template>
                 </el-table-column>
                 <el-table-column
                   align="center"
                   min-width="150"
                   label="加工商">
                   <template  slot-scope="scope">{{scope.row.agentProcessor}}</template>
                 </el-table-column>
                 <el-table-column
                   align="center"
                   min-width="100"
                   label="数量">
                   <template  slot-scope="scope">{{scope.row.goodsNum}}</template>
                 </el-table-column>
                 <el-table-column
                   align="center"
                   min-width="100"
                   label="加工费单价">
                   <template  slot-scope="scope">{{scope.row.processingFee}}</template>
                 </el-table-column>
                 <el-table-column
                   align="center"
                   min-width="100"
                   label="加工费总额">
                   <template  slot-scope="scope">{{scope.row.processingFeeAmount}}</template>
                 </el-table-column>
             </el-table>
        </el-form-item>
        <el-form-item label="合计金额：" >{{payForm.allNum}}</el-form-item>
        <el-form-item label="实际付款：" >
            <el-input style="width:150px;" v-model="payForm.applyPayAmount"></el-input>
        </el-form-item>
        <el-form-item label="付款方式：" >
          <el-radio-group v-model="payForm.applyPaymentCode">
            <el-radio label="cash">现金汇款</el-radio>
            <el-radio label="chengdui">承兑</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合同附件："  >
          <div style="width:80px;height:80px;margin-bottom:10px;margin-right:10px;vertical-align: middle;position: relative;display:inline-block" v-for="(item,index) in payForm.applyPayContract" :key="index">
            <img :src="item"  style="width:100%;height:100%;object-fit: contain;"/>
            <i class="el-icon-error" style="cursor: pointer;position: absolute;right:0;top:0;" @click="delImg(index)"></i>
          </div>
          <el-upload
            v-if="payForm.applyPayContract.length<3"
            class="avatar-uploader"
            action="https://upload.qiniup.com"
            :data="uploadToken"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="付款备注：">
            <el-input type="textarea" :rows="2" v-model="payForm.applyPayRemark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible=false">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {warehouseList,warehouseAdd,warehouseEdit,delWarehouse,} from '@/api/company'
import {getAddressList,getOrderUsersList,getQiniuToken,agentProcessBillList,agentProcessAddApplyPay} from '@/api/partner'
import {validateCommission} from '@/utils/validate';
import {formatDate} from '@/utils/date';
import store from '@/store'
import warehouseInfo from './warehouseInfo.vue'
import { mapGetters } from 'vuex'
import scheduling from "./scheduling";
import limit from "./limit";
const defaultListQuery={
  "tab":'all',
  "userId" : '',  //业务员
  "entrySn" : "", //单据编号
  "agentProcessor" : "",  //加工商
  "materialOrderSn" : "", //原料采购订单号
  "createTime" : [], //单据日期
  "processPayState" : '', //付款状态(0未付款，10付款申请中，20已付款))
  "pageNum" : 1,
  "pageSize" : 10
};
const defaultPayForm={
  "agentProcessor" : "",  //收款方
  "fromCompany" : "塑盟",  //付款方
  "pegIds" : '', //单据明细ID(多个逗号隔开)
  "allNum" : 0,
  "applyPayAmount" : 0,
  "applyPaymentCode" : "cash", //付款方式
  "applyPayContract" : [],  //合同附件
  "applyPayRemark" : "", //付款备注
};
export default {
  name: "index",
  data(){
    const validatePayAmount = (rule, value, callback) => {
      if (!validateCommission(parseFloat(value))) {
        callback(new Error('非负整数或小数'))
      } else if(value > this.priceForm.unPaidAmount){
        callback(new Error('收款金额大于未付金额'))
      }else {
        callback()
      }
    };
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData: [],
      count: 0,
      listLoading: false,
      userOptionList:[],
      roles:store.getters.roles ? store.getters.roles : [],
      btnLoading:false,
      payForm:JSON.parse(JSON.stringify(defaultPayForm)),
      rules:{},
      dialogVisible:false,
      uploadToken:{
        token:'',
      },
      imgDomain:'',
      selectProduct:[],
      btnloading5:false,
    }
  },
  components : {
    warehouseInfo:warehouseInfo
  },
  computed: {

  },
  created() {
    this.getUserOptionList();
    this.getList();
  },
  methods:{
    toInfo(item){
      let routeData = this.$router.resolve({name:'purchaseOEMInfo',query:{id:item.entryId}});
      window.open(routeData.href);
    },

    selectable(row,index) {
      if(row.processPayState==="未付款"){
        return true
      }else {
        return false
      }
    },
    changeTab(val){
      if(val == 'all'){
        this.listQuery.processPayState = ''
      }else{
        this.listQuery.processPayState = val == 'unpaid' ? 0 : 10
      }
      this.handleSearchList()
    },

    //下载excle
    downloadExcel(){
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      this.btnloading5 = true;
      agentProcessBillList(params).then((res)=>{
        this.btnloading5= false;
        require.ensure([], () => {
          const { export_json_to_excel } = require('sheet/Export2Excel');
          const tHeader = res.title;
          const filterVal = res.columns;
          const list = res.list;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, res.fileName);
        })
      }).catch(()=>{
        this.btnloading5 = false;
      })
    },

    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    //上传图片
    handleAvatarSuccess(res){
      this.payForm.applyPayContract.push(this.imgDomain+res.key)
    },

    //删除图片
    delImg(index){
      this.payForm.applyPayContract.splice(index,1)
    },

    //显示弹窗
    showPop(){
        if(this.selectProduct.length == 0){
          this.$message({
            message: '请先选择需付款的单据！',
            type: 'error'
          });
          return false
        }
        this.getUploadToken();
        this.payForm = JSON.parse(JSON.stringify(defaultPayForm));
        this.payForm.agentProcessor = this.selectProduct[0].agentProcessor;
        this.payForm.allNum = 0;
        this.payForm.applyPayAmount = 0;
        this.selectProduct.forEach((el)=>{
          this.payForm.allNum = this.payForm.allNum + parseFloat(el.processingFeeAmount);
          this.payForm.applyPayAmount = this.payForm.applyPayAmount + parseFloat(el.processingFeeAmount);
        })
        this.dialogVisible = true;
    },

    //获取七牛TOKEN
    getUploadToken(){
      getQiniuToken().then((res)=>{
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },

    //确认付款申请
    handleConfirm(){
      this.$refs.payForm.validate((valid) => {
        if (valid) {
          this.btnLoading2 = true;
          let data = JSON.parse(JSON.stringify(this.payForm));
            delete data.allNum;
            delete  data.agentProcessor;
            let pegIds = [];
            this.selectProduct.forEach((el)=>{
              pegIds.push(el.pegId)
            })
            data.pegIds = pegIds.join(",")
          agentProcessAddApplyPay(data).then(()=>{
            this.btnLoading = false;
            this.dialogVisible = false;
            this.getList().then(()=>{
              this.$nextTick(() => {
                this.$refs.multipleTable.clearSelection();
                this.selectProduct = [];
                this.$forceUpdate()
              })
            })
          }).catch(()=>{
            this.btnLoading = false;
          })
        }
      })
    },


    //切换选择单据
    handleSelectionChange(val){
       this.selectProduct = JSON.parse(JSON.stringify(val));
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList().then((res)=>{
        this.userOptionList = res;
      })
    },

    //删除
    delRow(item){
      this.$confirm('确定删除此仓库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delWarehouse({warehouseId:item.warehouseId}).then(()=>{
          this.getList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //显示增加收款弹窗
    showDialog(type,item){


    },



    handleSizeChange(val){
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val){
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList(){
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      this.listLoading = true;
        return agentProcessBillList(this.listQuery).then(response => {
          this.tableData = response.list;
          this.count = response.count;
          this.listLoading = false;
        }).catch(()=>{
          this.listLoading = false;
        });
    },

    //去收款单页
    toReceiptList(item){
      localStorage.setItem('accountingListQuery', JSON.stringify(this.listQuery));
      this.$router.push({name:'receiptList',query:{orderSn:item.orderSn}})
    },
  },
}
</script>

<style scoped lang="scss">
.avatar-uploader{
  margin-bottom:10px;
  display: inline-block;
  width:80px;
  height:80px;
  border:1px solid #DCDFE6;
  text-align: center;
  line-height: 80px;
  vertical-align: middle;
}
</style>
